package com;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encrypt {

    private String stringMD5(String mess) throws NoSuchAlgorithmException {

        MessageDigest messageDigest = MessageDigest.getInstance("MD5");

        byte[] bytes = mess.getBytes();

        messageDigest.update(bytes);

        byte[] res = messageDigest.digest();

        //return new String(res);
        //return byteArrayToHex(res);

        return DatatypeConverter.printHexBinary(res);

    }

    /**
     * 和DatatypeConverter.printHexBinary()一样作用
     * @param bytes
     * @return
     */
    private String byteArrayToHex(byte[] bytes){

        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };

        char[] resultCharArray = new char[bytes.length*2];

        int ind = 0;

        for(byte b: bytes){

            resultCharArray[ind++] = hexDigits[b>>4 & 0xf];

            resultCharArray[ind++] = hexDigits[b & 0xf];

        }

        return new String(resultCharArray);

    }


    public static void main(String[] args) {

        Encrypt encrypt = new Encrypt();

        try {
            System.out.println(encrypt.stringMD5("aasfasdfasdf"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

}
